package com.cn.txx.web.socket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.cn.txx.entity.User;
import com.cn.txx.utils.Constants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class MyWebSocketHandler implements WebSocketHandler{
	
	private static final Logger logger = Logger.getLogger(MyWebSocketHandler.class);
	
	// 保存所有的用户session
    public static final ArrayList<WebSocketSession> users = new ArrayList<WebSocketSession>();

	public void afterConnectionClosed(WebSocketSession session, CloseStatus arg1) throws Exception {
		logger.info("connect websocket closed.......");
		User user = (User) session.getHandshakeAttributes().get(Constants.CURRENT_USER);
        users.remove(session);
        TextMessage textMessage = new TextMessage(user.getT_NAME()+"以退出...", true);
        // 调用方法（发送消息给所有人）
        sendMsgToAllUsers(textMessage);
        logger.info(user.getT_NAME()+"以退出...");
	}

	/**
	 * 连接就绪
	 */
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		logger.info("connect websocket success.......");
        users.add(session);
        User user = (User) session.getHandshakeAttributes().get(Constants.CURRENT_USER);
        if(user!= null){
            //查询未读消息
           /* int count = webSocketService.getUnReadNews((String) session.getHandshakeAttributes().get(Constants.CURRENT_USER));

            session.sendMessage(new TextMessage(count + ""));*/
        }
        // 处理消息 msgContent消息内容
        TextMessage textMessage = new TextMessage(user.getT_NAME()+"以加入...", true);
        // 调用方法（发送消息给所有人）
        sendMsgToAllUsers(textMessage);
        logger.info(user.getT_NAME()+"以加入...");
	}

	/**
	 * 处理信息
	 */
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        Gson gson = new Gson();

        // 将消息JSON格式通过Gson转换成Map
        // message.getPayload().toString() 获取消息具体内容
        Map<String, Object> msg = gson.fromJson(message.getPayload().toString(), 
                new TypeToken<Map<String, Object>>() {}.getType());

        logger.info("handleMessage......."+message.getPayload()+"..........."+msg);

//      session.sendMessage(message);

        // 处理消息 msgContent消息内容
        TextMessage textMessage = new TextMessage(msg.get("msgContent").toString(), true);
        // 调用方法（发送消息给所有人）
        sendMsgToAllUsers(textMessage);
	}

	public void handleTransportError(WebSocketSession arg0, Throwable arg1) throws Exception {
		
	}

	public boolean supportsPartialMessages() {
		
		return false;
	}
	
	// 给所有用户发送 信息
    public void sendMsgToAllUsers(WebSocketMessage<?> message) throws Exception{

        for (WebSocketSession user : users) {
            user.sendMessage(message);
        }
    }
    
    /**
     * 给某个用户发送消息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {
        for (WebSocketSession user : users) {
            if (user.getHandshakeAttributes().get(Constants.CURRENT_USER).equals(userName)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
}
